<?php

namespace Core\http;
class Response
{
    protected $body;
    /**@var  $swoole_response \Swoole\Http\Response* */
    protected $swoole_response;

    /**
     * Response constructor.
     * @param \Swoole\Http\Response $response
     */
    public function __construct(\Swoole\Http\Response $response)
    {
        $this->swoole_response = $response;
        $this->swoole_response->header("Content-Type", "text/plain;charset=utf8");
    }

    public static function init(\Swoole\Http\Response $response)
    {
        $res = new self($response);
        return $res;
    }


    /**
     * @return mixed
     */
    public function getBody()
    {
        return $this->body;
    }

    /**
     * @param mixed $body
     */
    public function setBody($body): void
    {
        $this->body = $body;
    }

    public function setStatus(int $code)
    {
        $this->swoole_response->status($code);
    }


    public function setHeader($key, $value)
    {
        $this->swoole_response->header($key, $value);
    }

    public function write($string)
    {
        $this->swoole_response->write($string);
    }

    public function redirect($url, $code = 301)
    {
        $this->setStatus($code);
        $this->setHeader("Location", $url);
    }

    public function end()
    {
        $returnData = $this->getBody();
        switch (gettype($returnData)) {
            case "array":
            case "object":
                $this->setHeader("Content-Type", "application/json");
                $returnData = json_encode($returnData);
                break;
        }
        if ($returnData) {
            $this->swoole_response->write($returnData);
        }
        return $this->swoole_response->end();
    }


}
